package kubeclient

import (
	"context"
	"fmt"
	v1 "k8s.io/api/networking/v1"
	v12 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/yaml"
)

type IngressKubeController struct {
	*KubeController
}

func (ikc *IngressKubeController) Get(namespace string, application string) (interface{}, error) {
	ingressName := "ingress-" + application
	return ikc.ingressLister.Ingresses(namespace).Get(ingressName)
}

func (ikc *IngressKubeController) Create(namespace string, application string, domain string) (interface{}, error) {
	i := initIngress(domain, "ingress-"+application, application+"-service")
	return ikc.clientSet.NetworkingV1().Ingresses(namespace).Create(context.TODO(), i, v12.CreateOptions{})
}

func (ikc *IngressKubeController) Delete(namespace string, application string) error {
	ingressName := "ingress-" + application
	return ikc.clientSet.NetworkingV1().Ingresses(namespace).Delete(context.TODO(), ingressName, v12.DeleteOptions{})
}

func initIngress(domain string, ingressName string, serviceName string) *v1.Ingress {
	// Ingress
	var ingress = &v1.Ingress{}
	ingress.Name = ingressName
	ingress.Namespace = "n1"
	ingress.Annotations = make(map[string]string)
	ingress.Annotations["ingressclass.kubernetes.io/is-default-class"] = "true"
	ingress.Annotations["kubernetes.io/ingress.class"] = "nginx"

	// IngressRule
	var ingressRuleList []v1.IngressRule
	ingressRule := v1.IngressRule{}
	ingressRule.Host = domain
	// IngressHttpPaths
	var ingressRulePathList []v1.HTTPIngressPath
	ingressPath := v1.HTTPIngressPath{}
	pathType := v1.PathType("Prefix")
	ingressPath.PathType = &pathType
	ingressPath.Path = "/"
	backend := v1.IngressBackend{}
	ingressServiceBackend := v1.IngressServiceBackend{Name: serviceName, Port: v1.ServiceBackendPort{Number: 80}}
	backend.Service = &ingressServiceBackend
	ingressPath.Backend = backend

	//ingressRule.HTTP
	ingressRuleHttp := &v1.HTTPIngressRuleValue{}

	ingressRulePathList = append(ingressRulePathList, ingressPath)
	ingressRuleHttp.Paths = ingressRulePathList

	ingressRule.HTTP = ingressRuleHttp

	//= &v1.PathTypePrefix
	ingressRuleList = append(ingressRuleList, ingressRule)

	// 设置IngressRules
	ingress.Spec.Rules = ingressRuleList
	conf, _ := yaml.Marshal(&ingress)
	fmt.Println(string(conf))
	return ingress
}
